<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="参数类型" prop="dictType">
        <el-input
          v-model="queryParams.dictType"
          placeholder="请输入参数类型"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参数名称" prop="dictName">
        <el-input
          v-model="queryParams.dictName"
          placeholder="请输入参数名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dict:tree:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="treeList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column align="center" width="100" label="参数类型" prop="dictType" />
      <el-table-column align="center" width="120" label="参数名称" prop="dictName" />
      <el-table-column align="center" width="60" label="层级" prop="level" />
      <el-table-column align="center" width="60" label="等级" prop="grade" />
      <el-table-column align="center" width="100" label="等级类型" prop="gradeType" />
      <el-table-column align="center" width="120" label="等级名称" prop="gradeName" />
      <el-table-column align="center" width="150" label="级联类型" prop="fullType" />
      <el-table-column align="center" width="150" label="级联名称" prop="fullName" />
      <el-table-column align="center" label="备注" prop="remark" />

      <el-table-column align="center" width="150" label="操作" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dict:tree:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            :disabled="scope.row.level + 1 === scope.row.grade"
            @click="handleAdd(scope.row)"
            v-hasPermi="['dict:tree:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dict:tree:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改树表对话框 -->
    <el-dialog :title="model.title" :visible.sync="model.open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级节点" prop="parentId">
          <el-row>
            <el-col :span="12">
              <treeselect placeholder="上级" v-model="form.parentId" :options="treeOptions" :normalizer="normalizer"
                        :disable-branch-nodes="true" :flat="true" :multiple="false"
                        @select="changeNode" @input="changeNode2" />
            </el-col>
            <el-col :span="12"><span class="labelRemark">上级节点不可修改</span></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="层级" prop="level">
          <el-row>
            <el-col :span="4">
              <el-select v-model="form.level" :disabled="form.parentId !== 0" @change="changeLevel">
                <el-option v-for="dict in dictData.levels" :key="dict" :label="dict" :value="dict" />
              </el-select>
            </el-col>
            <el-col :span="20"><span class="labelRemark">可以扩展的下级数(一级节点配置)</span></el-col>
          </el-row>
        </el-form-item>
        <template  v-if="form.parentId == 0">
          <el-form-item label="参数类型" :required="true" :show-message="false">
            <el-row>
              <template v-if="form.level === 1">
                <el-col :span="24">
                  <el-form-item label="" label-width="0" prop="fullType">
                    <el-input v-model="form.fullType" placeholder="请输入参数类型" />
                  </el-form-item>
                </el-col>
              </template>
              <template v-else v-for="(key, idx) in dictData.levels">
                <el-col :span="Math.floor(24 / form.level)" v-if="idx < form.level">
                  <el-form-item label="" label-width="0" :prop="'fullType_' + (idx + 1)">
                    <el-input v-model="form['fullType_' + (idx + 1)]" :placeholder="'类型' + (idx + 1)"
                              @change="changeArr('fullType')"/>
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
          </el-form-item>
          <el-form-item label="参数名称" :required="true" :show-message="false">
            <el-row>
              <template v-if="form.level === 1">
                <el-col :span="24">
                  <el-form-item label="" label-width="0" prop="fullName">
                    <el-input v-model="form.fullName" placeholder="请输入参数名称" />
                  </el-form-item>
                </el-col>
              </template>
              <template v-else v-for="(key, idx) in dictData.levels">
                <el-col :span="Math.floor(24 / form.level)" v-if="idx < form.level">
                  <el-form-item label="" label-width="0" :prop="'fullName_' + (idx + 1)">
                    <el-input v-model="form['fullName_' + (idx + 1)]" :placeholder="'名称' + (idx + 1)"
                              @change="changeArr('fullName')"/>
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
          </el-form-item>
        </template>
        <el-form-item label="等级" prop="grade">
          <el-row>
            <el-col :span="4"><el-input v-model="form.grade" disabled /></el-col>
            <el-col :span="6" v-if="form.parentId !== 0"><el-input v-model="form.gradeType" disabled /></el-col>
            <el-col :span="6" v-if="form.parentId !== 0"><el-input v-model="form.gradeName" disabled /></el-col>
            <el-col :span="8"><span class="labelRemark">当前所在等级</span></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="form.dictType" :disabled="form.parentId === 0" placeholder="请输入类型" style="width: 50%;" />
        </el-form-item>
        <el-form-item label="名称" prop="dictName">
          <el-input v-model="form.dictName" :disabled="form.parentId === 0" placeholder="请输入名称" style="width: 50%;" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDomain, getDomain, delDomain, saveDomain } from "@/api/shengchan/dict";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "DictData",
  components: {
    Treeselect
  },
  data() {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 树表表格数据
      mapData: {},
      treeList: [],
      // 树表树选项
      treeOptions: [],
      title: "参数字典",
      model: {
        open: false,
        title: ""
      },
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        dictType: null,
        dictName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        level: [ { required: true, message: "层级不能为空", trigger: "blur" } ],
        grade: [ { required: true, message: "等级不能为空", trigger: "blur" } ],
        fullType: [ { required: true, message: "类型不能为空", trigger: "blur" } ],
        fullName: [ { required: true, message: "名称不能为空", trigger: "blur" } ],
        dictName: [ { required: true, message: "名称不能为空", trigger: "blur" } ]
      },
      dictData: {
        level: 6,
        levels: []
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询树表列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      listDomain(this.queryParams).then(res => {
        this.mapData = new Map();
        res.data.forEach(e => this.mapData.set(e.id, e));
        this.treeList = this.handleTree(res.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换树表数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      const disabled = node.id == 0 || (node.level && node.level + 1 == node.grade);
      return {
        id: node.id,
        label: node.dictName,
        isDisabled: true,
        children: node.children
      };
    },
    /** 查询树表下拉树结构 */
    getTreeselect() {
      listDomain().then(res => {
        this.treeOptions = [];
        const data = { id: 0, level: 0, dictName: '顶级节点', children: [] };
        data.children = this.handleTree(res.data, "id", "parentId");
        this.treeOptions.push(data);
      });
    },
    initDictRules(level) {
      if (this.form.parentId === 0) {
        let idx = 0
        Object.keys(this.rules).forEach(key => {
          if (key.indexOf('_') > 0) {
            delete this.rules[key];
            if (Math.floor(idx / 2) >= level) {
              this.form[key] = null
            }
            idx++;
          }
        });
        for (let i = 1; i <= level; i++) {
          this.rules['fullType_' + i] = [ { required: true, message: '类型' + i + '必填', trigger: 'blur' } ];
          this.rules['fullName_' + i] = [ { required: true, message: '名称' + i + '必填', trigger: 'blur' } ];
        }
        this.changeArr('fullType')
        this.changeArr('fullName')
      }
    },
    changeNode(data) {
      console.log(111, data)
      // const data = this.mapData.get(r.id)
      if (data.id) {
        this.form.level = data.level
        this.form.grade = data.grade + 1
        if (this.form.grade > this.form.level) {
          this.$modal.msgError("选择后的等级已超出最大层级，请修改");
        }
      } else {
        this.form.level = 1
        this.form.grade = 1
      }
    },
    changeNode2() {
      console.log(222)
    },
    changeLevel(level) {
      this.form.fullType = null
      this.form.fullName = null
      this.initDictRules(level)
    },
    changeArr(name) {
      const dict = name.replace('full', 'dict')
      const arr = []
      for(let i = 1; i <= this.form.level; i++) {
        arr.push(this.form[name + '_' + i])
      }
      this.form[name] = arr.join('/')
      this.form[dict] = arr[0]
    },
    // 取消按钮
    cancel() {
      this.model.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        dictType: null,
        dictName: null,
        level: 1,
        grade: 1,
        fullName: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    initDictLevel(min) {
      const level = this.dictData.level
      this.dictData.levels = []
      for (let i = min; i <= level; i++) {
        this.dictData.levels.push(i)
      }
    },
    initDictForm(level, start) {
      this.initDictRules(level)
      this.initDictLevel(start)
    },
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row !== null && row.id) {
        this.form.parentId = row.id
        this.form.topId = !row.topId ? row.id : row.topId
        this.form.level = row.level
        this.form.grade = row.grade + 1
        const data = !row.topId ? row : this.mapData.get(row.topId)
        console.log('add', data, row.grade)
        this.form.gradeType = data.fullType.split('/')[row.grade - 1]
        this.form.gradeName = data.fullName.split('/')[row.grade - 1]
      } else {
        this.form.parentId = 0
        this.form.topId = 0
        this.form.level = 1
        this.form.grade = 1
      }
      this.initDictForm(this.form.level, 1)
      this.model.open = true;
      this.model.title = "添加" + this.title;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.getTreeselect();
      if (row !== null) {
        this.form.parentId = row.id;
      }
      getDomain(row.id).then(res => {
        this.loading = false;
        this.form = res.data;
        this.initDictForm(this.form.level, (this.form.maxGrade || 2) - 1)
        this.model.open = true;
        this.model.title = "修改" + this.title;
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id === this.form.parentId) {
            this.$modal.msgError("不能选择本身作为上级");
            return
          }

          this.buttonLoading = true;
          saveDomain(this.form).then(res => {
            this.$modal.msgSuccess("保存成功");
            this.model.open = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.children) {
        return this.$modal.msgError("有下级记录不可删除");
      }
      this.$modal.confirm('是否确认删除数据项？').then(() => {
        this.loading = true;
        return delDomain(row.id);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    }
  }
};
</script>
<style scoped lang="scss">
  .labelRemark {
    padding-left: 10px;
    color: lightgray;
  }
</style>
